//
//  YiAudioRecoder.m
//  Yihubang
//
//  Created by xmy on 16/10/14.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "YiAudioRecoder.h"
#import "VoiceConverter.h"
@implementation YiAudioRecoder
//-(AVAudioRecorder *) initializeWith:(NSString *)filePath{
//    
//    return recorder;
//
//}

-(AVAudioRecorder *)recorder{
    if(!_recorder){
        AVAudioSession * audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
                      withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDuckOthers
                            error:nil]; //设置音频类别，这里表示当应用启动，停掉后台其他音频
        [audioSession setActive:YES error: nil];//设置当前应用音频活跃性
        NSDictionary *recordSetting = [VoiceConverter GetAudioRecorderSettingDict];
        NSURL * tmpFile = [NSURL fileURLWithPath:self.file_path];  //文件名的设置
        _recorder = [[ AVAudioRecorder alloc] initWithURL:tmpFile settings:recordSetting error:nil];
    }
    return _recorder;
}
-(NSString *)file_path{
    if(!_file_path){
        _file_path =[[NSString alloc]initWithString:[self getPathByFileNameWithType:@"wav"]];
    }
    return _file_path;
}
- (NSString*)getPathByFileNameWithType:(NSString *)_type
{
    NSString* fileDirectory = [[self getSavePath] stringByAppendingPathComponent:[[NSString stringWithFormat: @"%.0f", [NSDate timeIntervalSinceReferenceDate] * 1000.0] stringByAppendingPathExtension:_type]];
    return fileDirectory;
}
- (NSString *)getSavePath{
    //    NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/Audio", pathDocuments];
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return createPath;
}
- (NSString *)ConvertWavToAmrSavePath:(NSString *)aWavPath{
    NSString *newPath =[self getPathByFileNameWithType: @"amr"];
    [VoiceConverter ConvertWavToAmr:aWavPath amrSavePath:newPath];
    NSData* data=[NSData dataWithContentsOfFile:newPath];
    NSString* str=[data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength ];
    str=[@"data:audio/amr;base64,"stringByAppendingString:str];
    return str;
}
-(void)startToRecorder{
    [self.recorder prepareToRecord];
    [self.recorder record];
}
-(void)stopToRecorder{
    if([self.recorder isRecording]){
        [self.recorder stop];
        self.recorder = nil;
    }
}
-(void)uploadRecorderFinishedBlock:(RFAudioSuccessDetailBlock)success fail:(RFAudioFailDetailBlock)_fail{
    [[[HttpManagerCenter sharedHttpManager] uploadAudio:[self ConvertWavToAmrSavePath:self.file_path] resultClass:nil] subscribeNext:^(BaseModel *model){
        if(model.code==200){
            success(model);
        }else{
            _fail(model);
        }
    } error:^(NSError * error){
        [[MasterUrlManager shareMasterUrlManager].currentVC hiddenHUDWithString:@"上传失败" error:YES];
    }];
}

@end
